﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WorkStation.Frameworks.Core.Extensions;
using WorkStation.Frameworks.EasyBus.Pipeline.Filters;

namespace WorkStation.Frameworks.EasyBus.Pipeline.Handles
{
    /// <summary>
    /// 处理器
    /// </summary>
    public class Handle : IHandle
    {
        #region 私有变量

        /// <summary>
        /// 注册的委托处理内容
        /// </summary>
        protected Func<ActionContext, IHandle, HandleResult> _processFunc;

        #endregion

        #region 公有属性

        /// <summary>
        /// 唯一标识
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 过滤器
        /// </summary>
        public IFilter Filter { get; set; }

        /// <summary>
        /// 顺序
        /// </summary>
        public int Order { get; set; }

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name">唯一标识</param>
        /// <param name="filter">过滤器</param>
        public Handle(string name = null, IFilter filter = null, int order = -1)
        {
            if (string.IsNullOrEmpty(name))
            {
                this.Name = this.GetHashCode().ToString();
            }
            else
            {
                this.Name = name;
            }

            if (filter != null)
            {
                this.Filter = filter;
            }

            this.Order = order;
        }

        #endregion

        #region 公有方法

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="context">执行上下文</param>
        /// <returns></returns>
        public HandleResult Execute(ActionContext context)
        {
            if (!this.CanProcess(context.Input))
            {
                return new SuccessHandleResult(context.Input, this, "【{0}】处理器被过滤掉".Fmt(this.Name));
            }

            if (context.Args.ContainsKey(ActionContext.IGNORE_HANDLE_KEY))
            {
                List<string> handleName = context.Args[ActionContext.IGNORE_HANDLE_KEY] as List<string>;

                if (handleName != null && handleName.Contains(this.Name))
                {
                    return new SuccessHandleResult(context.Input, this, "【{0}】处理器被忽略掉".Fmt(this.Name));
                }
            }

            try
            {
                if (this._processFunc != null)
                {
                    return this._processFunc(context, this);
                }
                else
                {
                    return this.InnerExecute(context);
                }
            }
            catch (Exception ce)
            {
                return new FailHandleResult(context.Input, this, ce.ToString(), ce);
            }
        }

        /// <summary>
        /// 注册处理内容
        /// </summary>
        /// <param name="func">委托</param>
        /// <returns></returns>
        public IHandle RegisterHandle(Func<ActionContext, IHandle, HandleResult> func)
        {
            this._processFunc = func;

            return this;
        }

        #endregion

        #region 可重写私有方法

        /// <summary>
        /// 处理核心（继承要重写此方法）
        /// </summary>
        /// <param name="context">执行上下文</param>
        /// <returns></returns>
        protected virtual HandleResult InnerExecute(ActionContext context)
        {
            throw new NotImplementedException("继承的处理器要重写次方法");
        }

        /// <summary>
        /// 是否可以处理
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        protected virtual bool CanProcess(object input)
        {
            if (this.Filter == null)
            {
                return true;
            }
            else
            {
                return this.Filter.IsMatched(input);
            }
        }

        #endregion
    }
}
